package com.ynkbny.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynkbny.domain.Token;
import com.ynkbny.lgapi.YnBk;
import com.ynkbny.mapper.TokenMapper;
import com.ynkbny.service.TokenService;
import com.ynkbny.service.outsideinterface.MyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
* @author YY
* @description 针对表【token】的数据库操作Service实现
* @createDate 2023-08-01 10:00:29
*/
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, Token>
    implements TokenService{

    private static final Logger log = LoggerFactory.getLogger(TokenServiceImpl.class);

    @Resource
    private YnBk ynBk;

    @Resource
    private MyClient myClient;

    @Value("${laoGou.host}")
    private String host;

    @Value("${laoGou.login}")
    private String login;

    private static final String USERNAME = "ybbky";

    private static final String PASSWORD = "123456";

    /**
     * 获取老狗web Token
     *
     * @Author YY
     * @return 结果
     */
    @Override
    public String getLaoGouWebToken() {
        long seconds = DateUtil.currentSeconds();
        seconds -= 20*60;
        LambdaQueryWrapper<Token> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.gt(Token::getTime,String.valueOf(seconds));
        lambdaQueryWrapper.eq(Token::getId,1);

        Token token = this.getOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(token)){
            JSONObject loginResult = ynBk.login("ybbky","123456",false);
            log.info(loginResult.toJSONString());
            Token tokenObj = new Token();
            String data = loginResult.getString("data");
            tokenObj.setToken(data);
            tokenObj.setId(1);
            // 获取当前时间戳（秒级）
            tokenObj.setTime(String.valueOf(DateUtil.currentSeconds()));
            this.updateById(tokenObj);
            return data;
        }
        return token.getToken();
    }

    /**
     * 获取老狗 第三方通用API接口 token
     *
     * @Author juzipi123
     * @return 结果
     */
    @Override
    public String getLaoGouToken() {
        Long seconds = DateUtil.currentSeconds();
        LambdaQueryWrapper<Token> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询时间戳大于当前时间戳的token
        lambdaQueryWrapper.gt(Token::getTime,seconds.toString());
        lambdaQueryWrapper.eq(Token::getId,2);

        Token token = this.getOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(token)){
            String reqUrlLogin = host + login + "?username=" + USERNAME + "&password=" + PASSWORD;
            String login = myClient.login(reqUrlLogin);
            cn.hutool.json.JSONObject loginResult = JSONUtil.parseObj(login);
            Token tokenObj = new Token();
            String data = String.valueOf(loginResult.get("data"));
            tokenObj.setToken(data);
            tokenObj.setId(2);
            // 设置token过期时间为15分钟后
            seconds = DateUtil.currentSeconds();
            seconds += 15*60;
            tokenObj.setTime(String.valueOf(seconds));
            this.updateById(tokenObj);
            return data;
        }
        log.info("方法返回值（token）：{}",token.getToken());
        return token.getToken();
    }
}




